import jwt
import datetime
import secrets
from typing import Dict, Any, Optional
import hashlib



class AuthTokenManager:
    def __init__(self):
        self.secret_key = "your-super-secret-key-change-in-production"
        self.algorithm = "HS256"
        self.refresh_secret_key = "your-refresh-secret-key"

    def generate_access_token(self, user_data: Dict[str, Any]) -> str:
        """
        生成访问Token (短期)
        """
        payload = {
            **user_data,
            "token_type": "access",
            "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=2),
            "iat": datetime.datetime.utcnow(),
            "jti": secrets.token_urlsafe(16)  # JWT ID
        }

        return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)

    def generate_refresh_token(self, user_id: int) -> str:
        """
        生成刷新Token (长期)
        """
        payload = {
            "user_id": user_id,
            "token_type": "refresh",
            "exp": datetime.datetime.utcnow() + datetime.timedelta(days=30),
            "iat": datetime.datetime.utcnow(),
            "jti": secrets.token_urlsafe(16)
        }

        return jwt.encode(payload, self.refresh_secret_key, algorithm=self.algorithm)

    def verify_access_token(self, token: str) -> Optional[Dict[str, Any]]:
        """
        验证访问Token
        """
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
            if payload.get("token_type") != "access":
                return None
            return payload
        except jwt.PyJWTError:
            return None

    def verify_refresh_token(self, token: str) -> Optional[Dict[str, Any]]:
        """
        验证刷新Token
        """
        try:
            payload = jwt.decode(token, self.refresh_secret_key, algorithms=[self.algorithm])
            if payload.get("token_type") != "refresh":
                return None
            return payload
        except jwt.PyJWTError:
            return None

    def refresh_tokens(self, refresh_token: str) -> Optional[Dict[str, str]]:
        """
        使用刷新Token获取新的访问Token
        """
        payload = self.verify_refresh_token(refresh_token)
        if not payload:
            return None

        # 生成新的访问Token
        user_data = {
            "user_id": payload["user_id"],
            "username": payload.get("username", "")
        }

        new_access_token = self.generate_access_token(user_data)

        return {
            "access_token": new_access_token,
            "token_type": "Bearer",
            "expires_in": 7200  # 2小时
        }


def generateToken(userName,deltaDays,deltaHours):

    # 准备要编码的数据
    payload = {
        'userName': userName,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=deltaDays, hours=deltaHours)  # 设置过期时间
    }

    # 设置密钥，用于生成和验证token
    # secret_key = 'your_secret_key'

    secret_key = hashlib.md5(userName.encode('utf-8')).hexdigest()       #     md5_hash

    print(" secret_key = ")
    print(secret_key)
    # 生成token
    token = jwt.encode(payload, secret_key, algorithm='HS256')

    print(token)

    return token


def verifyToken(tokenId,username):

        try:
            secret_key = hashlib.md5(username.encode('utf-8')).hexdigest()  # md5_hash
            decoded_token = jwt.decode(tokenId, secret_key, algorithms=['HS256'])
            print("Token is valid.")
            print("Decoded token:", decoded_token)
            return  1
        except jwt.ExpiredSignatureError:
            print("Token has expired.")
            return  0
        except jwt.exceptions.DecodeError:
            print("Invalid token.")
            return  0
        except Exception as e:
            print("An error occurred:", e)
            return 0





# 使用示例
auth_manager = AuthTokenManager()

# 用户登录成功后生成tokens
user_info = {
    "user_id": 123,
    "username": "admin",
    "role": "administrator",
    "permissions": ["user:read", "user:write"]
}

access_token = auth_manager.generate_access_token(user_info)
refresh_token = auth_manager.generate_refresh_token(123)

print(f"Access Token: {access_token}")
print(f"Refresh Token: {refresh_token}")

# 验证Token
payload = auth_manager.verify_access_token(access_token)
if payload:
    print(f"用户ID: {payload['user_id']}")
    print(f"用户名: {payload['username']}")



generateToken("test",1,0)


